const {Api, JsonRpc, JsSignatureProvider, Numeric, RpcError} = require('icbsc.js');
const fetchFunc = require('node-fetch');

const util = require("./util.js").util;
const app = getApp();

module.exports = {
  // 创建随机账户名的区块链账户, 并且通过 util.setStorage 存储私钥
  async createBlockchainAccount(accountName, keyPair) {

    let isAccountExits = false;

    try {
      const blockchainAccount = await util.getStorage("blockchainAccount");
      isAccountExits = true;
    } catch (error) {
      console.log(error);
    }

    return new Promise((resolve, reject)=> {
      // 账户已经存在,不在重复创建
      if (isAccountExits) {
        return reject('区块链账户名已存在,不再重新创建');
      }

      const pubKey = keyPair.pubKey;
      console.log(keyPair);

      // 调用接口创建区块链账户
      wx.request({
        url: app.globalData.serverAddress + '/v1/service/create_account',
        method: 'POST',
        data: {
          accountName: accountName,
          publicKey: pubKey
        },
        header: {
          'content-type': 'application/json'
        },
        success (res) {
          
          if (res.statusCode == 200 && res.data.code == 0) {
            
            // 存储区块链账户名与私钥
            util.setStorage("blockchainAccount", accountName);
            util.setStorage("blockchainPrivateKey", keyPair.priKey);
            util.setStorage("blockchainPublicKey", keyPair.pubKey);
            resolve(accountName);
          } else if (res.data.code == -10) {
            reject('账户名已存在');
          } else {
            reject('账户创建失败');
          }
        },
        fail (error){
          console.error(error);
          reject();
        }
      });
    });
  },
  /*
   * @api 将数据写入区块
   * @apiParam {Object} actions 业务数据
   */
  async blockchainSet(actions){
    try {
      let isPrivateKeyExits = false;
      let privateKey = '';

      // 读取小程序存储的私钥
      try {
        privateKey = await util.getStorage("blockchainPrivateKey");
        isPrivateKeyExits = true;
      } catch (error) {
        console.log(error);
      }
      // 未找到私钥
      if (!isPrivateKeyExits) {
        console.log('未找到区块链账户的私钥,请先创建区块链账户');
        return;
      }

      // 将私钥导入 JsSignatureProvider

      const signatureProvider = new JsSignatureProvider([privateKey]);
      const rpc = new JsonRpc(app.globalData.nodeAddress,{fetchFunc});

      const api = new Api({rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder()});

      // 发起入链请求
      const result = await api.transact({
        actions: actions
      }, {
        blocksBehind: 3,
        expireSeconds: 150
      }).catch(err => {
        console.log('\nCaught exception: ' + err);
        if (err instanceof RpcError)
          console.log(JSON.stringify(err.json, null, 2));
      });

      return result.transaction_id;
    } catch (error) {
      console.log(error);
    }
  }
};